package com.cxria.activemq.web.controller;

import com.cxria.activemq.entity.Message;
import com.cxria.activemq.service.ConsumerService;
import com.cxria.activemq.service.ProducerService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jms.Destination;
import javax.jms.TextMessage;

@Controller
@RequestMapping("/jms")
public class JmsController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ProducerService producerService;

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    //@Qualifier("queueDestination")
    private Destination queueDestination;

    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("/send")
    @ResponseBody
    public String send(Message message) throws Exception {
        //发送更新数据请求
        producerService.sendMessage(queueDestination, objectMapper.writeValueAsString(message));
        return "send success";
    }

    @PostMapping("/receive")
    @ResponseBody
    public Message receive(Message message) throws Exception {
        TextMessage tm = consumerService.receive(queueDestination);
        Message msg = objectMapper.readValue(tm.getText(), Message.class);
        return msg;
    }

}
